"""
项目初始化涉及方法

"""
from uuid import uuid4
from flask import request, g
from flask_cors import CORS
from components.memcache.connector import cache
from components.mysql.connector import db
from components.base_exception import *
from components.base_log import CustomLogger
from components.nacos.service import register_service, send_heartbeat_thread
from utils.views import resp_with_data
from views.user import user_bp
from views.role import role_bp
from views.org import org_bp


def register_blueprints(app):
    app.register_blueprint(user_bp, url_prefix='/user')
    app.register_blueprint(org_bp, url_prefix='/org')
    app.register_blueprint(role_bp, url_prefix='/role')


def register_middleware(app):
    @app.before_request
    def request_to_g():
        # 搜索字段
        authorization = request.headers.get('Authorization')
        # 如果 Authorization 头不存在，authorization_header 将会是 None
        if authorization:
            g.token = authorization
            if not g.token:
                return resp_with_data(10006)
            if not cache.get(g.token.encode('utf-8')):
                return resp_with_data(10007)
            info = json.loads(cache.get(g.token.encode('utf-8')))
            g.user_id = info['id']
            g.org_ids = info['org_ids']
            g.real_org_ids = info['real_org_ids']
            g.erp_ids = info['erp_ids']
        else:
            path_list = request.path.split('/')
            if path_list[1] not in ['static', 'common', 'public']:
                return resp_with_data(10011)
        args_dict = {}
        for arg, value in request.args.items():
            args_dict[arg] = value
            if arg.startswith('search_'):
                # 过滤所有搜索中为bool值的搜索参数
                value = value.strip()
                if value == 'true':
                    value = True
                if value == 'false':
                    value = False
                setattr(g, arg, value)
        # 分页字段
        g.page = int(request.args.get('page') or 0)
        g.per_page = int(request.args.get('per_page') or 10)
        # 请求体
        g.json = request.get_json(silent=True) or {}
        g.files = request.files
        g.params = {
            "GET": args_dict,
            "POST": g.json
        }
        g.request_id = uuid4()
        g.remote_addr = request.remote_addr

    @app.before_request
    def connect_database():
        if db.is_closed():
            db.connect()

    @app.teardown_request
    def close_database(response):
        db.close()


def register_log(app):
    custom_logger = CustomLogger(__name__)
    app.logger = custom_logger
    app.logger.setLevel(app.config['LOG_LEVEL'])


def register_exception(app):
    cls_list = [cls for cls in globals().values() if isinstance(cls, type) and issubclass(cls, APIException)]
    for cls in cls_list:
        @app.errorhandler(cls)
        def _(exc):
            return jsonify({"code": exc.code, "message": exc.message, "data": ""})


def register_commands(app):
    @app.cli.command()
    def createtables():
        # 用于临时生成数据库表
        # db.create_tables([EnumData])
        pass

    # @app.cli.command()
    # def smqtt():
    #     try:
    #         mqtt = MQTT()
    #         mqtt.forever()
    #     except Exception as e:
    #         print(e)


def register_extensions(app):
    cors = CORS()
    cors.init_app(app)


# 发送到Nacos服务注册接口
def register_heartbeat_to_nacos():
    register_service()
    send_heartbeat_thread()
